#!/usr/bin/env python3
"""
增强版主窗口

集成新的Tab页面：
- 转码任务管理
- 硬件监控
- 系统设置
"""

import sys
from pathlib import Path

from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QTabWidget, QStatusBar, QMenuBar, QMenu)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont, QAction

# 导入新的Tab组件
from .transcode_tasks_tab import TranscodeTasksTab
from .hardware_monitor_tab import HardwareMonitorTab
from .settings_tab import SettingsTab


class VideoTranscoderAppEnhanced(QMainWindow):
    """增强版视频转码系统主窗口"""
    
    def __init__(self):
        super().__init__()
        self.update_timer = QTimer()
        self.init_ui()
        self.init_signals()
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("视频转码系统 v2.0")
        self.setGeometry(100, 100, 1400, 875)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 标签页控件
        self.tab_widget = QTabWidget()
        
        # 转码任务标签页
        self.tasks_tab = TranscodeTasksTab()
        self.tab_widget.addTab(self.tasks_tab, "📹 转码任务")
        
        # 硬件监控标签页
        self.monitor_tab = HardwareMonitorTab()
        self.tab_widget.addTab(self.monitor_tab, "📈 硬件监控")
        
        # 系统设置标签页
        self.settings_tab = SettingsTab()
        self.tab_widget.addTab(self.settings_tab, "⚙️ 系统设置")
        
        main_layout.addWidget(self.tab_widget)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("系统就绪 - 欢迎使用视频转码系统 v2.0")
        
        # 菜单栏
        self.create_menu_bar()
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menu_bar = self.menuBar()
        
        # 文件菜单
        file_menu = menu_bar.addMenu("文件(&F)")
        
        new_task_action = QAction("新建任务", self)
        new_task_action.setShortcut("Ctrl+N")
        new_task_action.triggered.connect(self.add_transcode_task)
        file_menu.addAction(new_task_action)
        
        open_task_action = QAction("打开任务", self)
        open_task_action.setShortcut("Ctrl+O")
        open_task_action.triggered.connect(self.open_transcode_task)
        file_menu.addAction(open_task_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 视图菜单
        view_menu = menu_bar.addMenu("视图(&V)")
        
        tasks_action = QAction("转码任务", self)
        tasks_action.setShortcut("Ctrl+1")
        tasks_action.triggered.connect(lambda: self.tab_widget.setCurrentIndex(0))
        view_menu.addAction(tasks_action)
        
        monitor_action = QAction("硬件监控", self)
        monitor_action.setShortcut("Ctrl+2")
        monitor_action.triggered.connect(lambda: self.tab_widget.setCurrentIndex(1))
        view_menu.addAction(monitor_action)
        
        settings_action = QAction("系统设置", self)
        settings_action.setShortcut("Ctrl+3")
        settings_action.triggered.connect(lambda: self.tab_widget.setCurrentIndex(2))
        view_menu.addAction(settings_action)
        
        # 工具菜单
        tools_menu = menu_bar.addMenu("工具(&T)")
        
        refresh_action = QAction("刷新数据", self)
        refresh_action.setShortcut("F5")
        refresh_action.triggered.connect(self.refresh_data)
        tools_menu.addAction(refresh_action)
        
        # 帮助菜单
        help_menu = menu_bar.addMenu("帮助(&H)")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)
        
        docs_action = QAction("文档", self)
        docs_action.setShortcut("F1")
        docs_action.triggered.connect(self.show_documentation)
        help_menu.addAction(docs_action)
    
    def init_signals(self):
        """初始化信号连接"""
        # 设置定时器，每秒更新一次数据
        self.update_timer.timeout.connect(self.update_display)
        self.update_timer.start(1000)  # 1秒更新一次
    
    def add_transcode_task(self):
        """添加转码任务"""
        # 这里应该打开转码任务对话框
        self.status_bar.showMessage("准备添加新的转码任务...")
        
        # 模拟添加任务（实际应该从对话框获取）
        self.simulate_task_addition()
    
    def open_transcode_task(self):
        """打开转码任务"""
        self.status_bar.showMessage("打开转码任务功能开发中...")
    
    def refresh_data(self):
        """刷新数据"""
        self.status_bar.showMessage("正在刷新数据...")
        self.update_display()
        self.status_bar.showMessage("数据刷新完成")
    
    def show_about_dialog(self):
        """显示关于对话框"""
        # 这里应该显示关于对话框
        self.status_bar.showMessage("显示关于信息...")
    
    def show_documentation(self):
        """显示文档"""
        self.status_bar.showMessage("打开系统文档...")
    
    def update_display(self):
        """更新显示数据"""
        # 获取模拟数据
        task_data = self.get_simulated_task_data()
        hardware_data = self.get_simulated_hardware_data()
        
        # 更新转码任务标签页
        self.tasks_tab.update_task_data(task_data)
        
        # 更新硬件监控标签页
        self.monitor_tab.update_hardware_data(hardware_data)
        
        # 更新状态栏
        self.update_status_bar(task_data, hardware_data)
    
    def get_simulated_task_data(self):
        """获取模拟任务数据"""
        return {
            'stats': {
                'total': 6,  # CPU:1 + 集显:2 + 独显:3 = 6
                'cpu': 1,
                'igpu': 2,  # 集显任务默认2个
                'dgpu': 3,  # 独显任务默认3个
                'completed': 5,
                'processing': 6,  # 正在处理的任务数等于总任务数
                'waiting': 2
            },
            'cpu_tasks': [
                {
                    'filename': 'video_sample_001.mp4',
                    'progress': 45,
                    'current_time': '00:12:30',
                    'total_time': '00:27:45',
                    'speed': '1.2x',
                    'bitrate': '4500k',
                    'fps': '29.97'
                }
            ],
            'igpu_tasks': [
                {
                    'filename': 'video_sample_002.mkv',
                    'progress': 78,
                    'current_time': '00:45:15',
                    'total_time': '00:58:00',
                    'speed': '0.8x',
                    'bitrate': '3200k',
                    'fps': '25.00'
                },
                {
                    'filename': 'video_sample_004.mp4',
                    'progress': 32,
                    'current_time': '00:08:20',
                    'total_time': '00:26:00',
                    'speed': '1.5x',
                    'bitrate': '2800k',
                    'fps': '30.00'
                }
            ],
            'dgpu_tasks': [
                {
                    'filename': 'video_sample_003.avi',
                    'progress': 22,
                    'current_time': '00:05:30',
                    'total_time': '00:25:00',
                    'speed': '2.1x',
                    'bitrate': '6000k',
                    'fps': '30.00'
                },
                {
                    'filename': 'video_sample_005.mov',
                    'progress': 65,
                    'current_time': '00:22:10',
                    'total_time': '00:34:00',
                    'speed': '1.8x',
                    'bitrate': '5200k',
                    'fps': '24.00'
                },
                {
                    'filename': 'video_sample_006.wmv',
                    'progress': 15,
                    'current_time': '00:03:45',
                    'total_time': '00:25:00',
                    'speed': '3.2x',
                    'bitrate': '3800k',
                    'fps': '29.97'
                }
            ]
        }
    
    def get_simulated_hardware_data(self):
        """获取模拟硬件数据"""
        import random
        
        return {
            'cpu': {
                'usage': random.randint(30, 80),
                'temperature': random.randint(40, 75),
                'frequency': random.randint(2500, 4200),
                'cores': 8
            },
            'igpu': {
                'usage': random.randint(10, 60),
                'memory_usage': random.randint(20, 80),
                'temperature': random.randint(35, 65),
                'frequency': random.randint(800, 1500)
            },
            'dgpu': {
                'usage': random.randint(40, 90),
                'memory_usage': random.randint(30, 95),
                'temperature': random.randint(45, 85),
                'frequency': random.randint(1200, 2000)
            },
            'memory': {
                'total': 17179869184,  # 16GB
                'used': random.randint(4294967296, 12884901888),  # 4-12GB
                'available': 17179869184 - random.randint(4294967296, 12884901888),
                'usage': random.randint(25, 75)
            },
            'storage': {
                'read_speed': random.randint(100000000, 500000000),  # 100-500 MB/s
                'write_speed': random.randint(50000000, 300000000),  # 50-300 MB/s
                'usage': random.randint(40, 90),
                'available': random.randint(50000000000, 200000000000)  # 50-200GB
            }
        }
    
    def update_status_bar(self, task_data, hardware_data):
        """更新状态栏"""
        total_tasks = task_data['stats']['total']
        cpu_usage = hardware_data['cpu']['usage']
        
        message = f"运行中: {total_tasks}个任务 | CPU使用率: {cpu_usage}% | 系统正常"
        self.status_bar.showMessage(message)
    
    def simulate_task_addition(self):
        """模拟任务添加"""
        # 这里应该实际添加任务到任务队列
        self.status_bar.showMessage("模拟添加转码任务...")


def main():
    """主函数"""
    from PyQt6.QtWidgets import QApplication
    
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle('Fusion')
    
    window = VideoTranscoderAppEnhanced()
    window.show()
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()